#coding:utf-8

#图片网址、库名、保存文件名
import urllib
def qiniufetch(url,bucket,filename):
  """调用七牛的fetch API 将url的图片存储到七牛"""
  from base64 import urlsafe_b64encode as b64e
  from qiniu.auth import digest
  access_key = "NBScwpaRBXnjELi06Um70F4HqcSy64YhcMnHFCGH"
  secret_key = "7PHaFCQMGRYICSRt26f8mO_YS0_iLcDwNjuTvpIe"

  encoded_url = b64e(url)
  dest_entry = "%s:%s" % (bucket, filename)
  encoded_entry = b64e(dest_entry.encode('utf-8'))

  api_host = "iovip.qbox.me"
  api_path = "/fetch/%s/to/%s" % (encoded_url, encoded_entry)

  mac = digest.Mac(access=access_key, secret=secret_key)
  client = digest.Client(host=api_host, mac=mac)

  ret, err = client.call(path=api_path)
  if err is not None:
    print "Fetch image file\"%s\" failed" % url
    print err
    return None
  else:
    print "Fetch \"%s\" to qiniu \"%s\" success!" % (url,dest_entry)
    return "http://%s.qiniudn.com/%s" % (bucket,urllib.quote(filename.encode('utf-8')))